package com.livepass.android.girlspicks.activities;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.AppEventsLogger;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;
import com.livepass.android.girlspicks.MyApplication;
import com.livepass.android.girlspicks.R;
import com.livepass.android.girlspicks.adapters.ArticleTableAdapter;
import com.livepass.android.girlspicks.adapters.CommentAdapter;
import com.livepass.android.girlspicks.models.Article;
import com.livepass.android.girlspicks.models.Comment;
import com.livepass.android.girlspicks.utils.GestureListener;
import com.livepass.android.girlspicks.utils.JSONParser;
import com.livepass.android.girlspicks.utils.Utilities;
import com.livepass.android.girlspicks.views.ScrollExpandListView;

@SuppressLint("ClickableViewAccessibility")
public class ArticleActivity extends Activity {

	ScrollExpandListView elvListComment;
	private View llButtonBottom;
	TextView tvArticleTitle;
	TextView tvOrgSitename;
	TextView tvArticleOverview;
	LinearLayout llBookmark;
	TextView tvBookmark;
	private LinearLayout llLoading;

	public Article article;
	private ArrayList<Comment> listComments;
	Map<String, List<Comment>> listReplys;
	private boolean isBookmark;
	private boolean isReadMore = false;
	private CommentAdapter commentAdapter;
	private AsyncGetCommentList loader;
	private AsyncPostComment loaderPostComment;
	private AsyncSetBookmark loaderBookmark;
	private AsyncRemoveBookmark loaderRemoveBookmark;
	private AsyncSetShareInApp loaderShareInApp;

	private UiLifecycleHelper uiHelper;
	private ArticleTableAdapter articleTableAdapter;

	@SuppressLint("ClickableViewAccessibility")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_article);

		// database
		// baseDAO = BaseDAO.getDBAdapterInstance(getApplicationContext());
		articleTableAdapter = ArticleTableAdapter
				.getInstance(getApplicationContext());

		article = (Article) getIntent().getExtras().get("article");
		// rlArticle = (RelativeLayout) findViewById(R.id.rlArticle);
		llLoading = (LinearLayout) findViewById(R.id.llLoading);
		elvListComment = (ScrollExpandListView) findViewById(R.id.list_comment);
		llButtonBottom = findViewById(R.id.llButtonBottom);

		listComments = new ArrayList<Comment>();
		// List comments
		loader = new AsyncGetCommentList();
		loader.execute(article.getArticleId());
		addHeaderView();

		tvArticleTitle = (TextView) findViewById(R.id.tvArticleTitle);
		tvOrgSitename = (TextView) findViewById(R.id.tvNewspaper);
		tvArticleOverview = (TextView) findViewById(R.id.tvArticleContent);
		llBookmark = (LinearLayout) findViewById(R.id.llButtonBookmark);
		tvBookmark = (TextView) findViewById(R.id.tvBookmark);
		if ("1".equals(articleTableAdapter.getArticleId(article.getArticleId()))) {
			llBookmark.setSelected(true);
			tvBookmark.setText(getString(R.string.btnBookmarkAlready)
					.toString().trim());
			isBookmark = true;
		} else {
			llBookmark.setSelected(false);
			tvBookmark.setText(getString(R.string.btnBookmarkNotyet).toString()
					.trim());
			isBookmark = false;
		}

		tvArticleTitle.setText(article.getTitle());
		tvOrgSitename.setText(article.getSite());
		tvArticleOverview.setText(article.getOverview());

		// List Replys
		listReplys = new LinkedHashMap<String, List<Comment>>();

		commentAdapter = new CommentAdapter(this, listComments, listReplys,	article);
		elvListComment.setAdapter(commentAdapter);
		elvListComment
				.setOnDetectScrollListener(new ScrollExpandListView.OnDetectScrollListener() {

					@Override
					public void onUpScrolling() {
						// llButtonBottom.setVisibility(View.VISIBLE);
					}

					@Override
					public void onDownScrolling() {
						// llButtonBottom.setVisibility(View.GONE);
					}
				});
		final GestureDetector gestureDetector = new GestureDetector(
				new GestureListener(ArticleActivity.this));
		elvListComment.setOnTouchListener(new View.OnTouchListener() {
			private float lastY;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_MOVE) {
					if (event.getRawY() > lastY) {
						llButtonBottom.setVisibility(View.VISIBLE);
					} else {
						llButtonBottom.setVisibility(View.GONE);
					}
					lastY = event.getRawY();
				}
				// for swipe left to right
				if (gestureDetector.onTouchEvent(event)) {
					overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
					return true;
				}
				return false;
			}
		});

		// share facebook
		uiHelper = new UiLifecycleHelper(this, null);
		uiHelper.onCreate(savedInstanceState);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();

		// Call the 'deactivateApp' method to log an app event for use in
		// analytics and advertising
		// reporting. Do so in the onPause methods of the primary Activities
		// that an app may be launched into.
		AppEventsLogger.deactivateApp(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(commentAdapter!=null && isReadMore) {
			// List comments
			loader = new AsyncGetCommentList();
			loader.execute(article.getArticleId());
		}
		isReadMore = false;
	}
	
	private void addHeaderView() {
		View view = LayoutInflater.from(this).inflate(R.layout.article_header,
				elvListComment, false);
		elvListComment.addHeaderView(view);
	}

	public void doBookmark(View v) {
		//insert into server
		if(isBookmark) {
			loaderRemoveBookmark = new AsyncRemoveBookmark();
			loaderRemoveBookmark.execute(article.getArticleId());
		} else {
			loaderBookmark = new AsyncSetBookmark();
			loaderBookmark.execute(article.getArticleId());
		}
	}

	public void doReadmore(View v) {
		Intent intentReadMore = new Intent(this, ReadMoreActivity.class);
		intentReadMore.putExtra("org_url", article.getUrl());
		Bundle bun = new Bundle();
		bun.putSerializable("article", article);
		intentReadMore.putExtras(bun);
		//startActivityForResult(intentReadMore, MyApplication.COMMENT);
		startActivity(intentReadMore);
		isReadMore = true;
	}

	public void doShare(View view) {
		final String link = MyApplication.APP_LINK_GLOBAL + "id="
				+ article.getArticleId() + "&cat_id=" + article.getCategoryId();
		ArrayList<String> items;
		items = new ArrayList<String>();
		items.add("Facebookでシェア");
		items.add("Twitterでシェア");
		items.add("LINEでシェア");
		items.add("リンクをコピー");
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setItems(items.toArray(new CharSequence[items.size()]),
				new DialogInterface.OnClickListener() {
					@SuppressLint("NewApi")
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							if (Utilities.isPackageExisted(
									getApplicationContext(),
									"com.facebook.katana")) {
								FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
										ArticleActivity.this).setLink(link)
										.setPicture(!"".equals(article.getImage())?article.getImage():"http://girlspicks.co/img/icon.png")
										.setCaption("Girls Picks")
										.setDescription(article.getOverview())
										.setName(article.getTitle())
										.setPlace("place").build();
								uiHelper.trackPendingDialogCall(shareDialog
										.present());
							} else {
								// Uri uri =
								// Uri.parse("https://play.google.com/store/apps/details?id=com.facebook.katana");
								Uri uri = Uri
										.parse("https://www.facebook.com/sharer/sharer.php?u="
												+ link);
								Intent intent = new Intent(Intent.ACTION_VIEW,
										uri);
								startActivity(intent);
							}
							loaderShareInApp = new AsyncSetShareInApp();
							loaderShareInApp.execute(article.getArticleId(), "1");
							break;
						case 1:
							Intent intentTwitter = new Intent(
									Intent.ACTION_VIEW);
							intentTwitter.setData(Uri
									.parse("http://twitter.com/share?url="
											+ article.getTitle()+ "\n" + link + "&count=horiztonal"));
							startActivity(intentTwitter);
							loaderShareInApp = new AsyncSetShareInApp();
							loaderShareInApp.execute(article.getArticleId(), "2");
							break;
						case 2:
							Intent intentLine;
							if (!Utilities.isPackageExisted(
									getApplicationContext(),
									"jp.naver.line.android")) {
								Uri uri = Uri
										.parse("https://play.google.com/store/apps/details?id=jp.naver.line.android");
								// Uri uri =
								// Uri.parse("https://www.facebook.com/sharer/sharer.php?u="
								// + article.getOrgUrl());
								intentLine = new Intent(Intent.ACTION_VIEW, uri);
								startActivity(intentLine);
							} else {
								intentLine = new Intent(Intent.ACTION_SEND);
								intentLine.setType("text/plain");
								intentLine.putExtra(Intent.EXTRA_TEXT, link);

								PackageManager pm = getPackageManager();
								Intent sendIntent = new Intent(
										Intent.ACTION_SEND);
								sendIntent.setType("text/plain");
								List<ResolveInfo> resInfo = pm
										.queryIntentActivities(sendIntent, 0);
								for (int i = 0; i < resInfo.size(); i++) {
									ResolveInfo ri = resInfo.get(i);
									String packageName = ri.activityInfo.packageName;
									if (packageName
											.contains("jp.naver.line.android")) {

										intentLine.setClassName(
												ri.activityInfo.packageName,
												ri.activityInfo.name);
										startActivity(intentLine);
									}
								}

							}
							break;
						case 3:
							Toast.makeText(getApplicationContext(),
									"Copied link", Toast.LENGTH_SHORT).show();
							int sdk = android.os.Build.VERSION.SDK_INT;
							if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
								android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
								clipboard.setText(link);
							} else {
								android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
								android.content.ClipData clip = android.content.ClipData
										.newPlainText("Copied Text", link);
								clipboard.setPrimaryClip(clip);
							}
							break;
						default:
							break;
						}
					}
				});
		builder.create().show();
	}

	public void doBack(View view) {
		Intent intent = new Intent();
		intent.putExtra("cmt_count", ""+listComments.size());
		setResult(RESULT_OK, intent);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		finish();
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
		intent.putExtra("cmt_count", ""+listComments.size());
		setResult(RESULT_OK, intent);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		finish();
	}
	
	public void doComment(View view) {
		Intent intent = new Intent(this, PushCommentReplyActivity.class);
		Bundle bun = new Bundle();
		bun.putSerializable("article", article);
		intent.putExtra(MyApplication.WHERE, MyApplication.COMMENT);
		intent.putExtras(bun);
		startActivityForResult(intent, MyApplication.COMMENT);
		isReadMore = false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == MyApplication.COMMENT) {
			if (resultCode == RESULT_OK) {
				String commentString = data.getStringExtra("comment");
				loaderPostComment = new AsyncPostComment(
						article.getArticleId(), commentString);
				loaderPostComment.execute();
			}
		} else if (requestCode == MyApplication.REPLY) {
			commentAdapter.onActivityResult(requestCode, resultCode, data);
		}
		// facebook
		uiHelper.onActivityResult(requestCode, resultCode, data,
				new FacebookDialog.Callback() {
					@Override
					public void onError(FacebookDialog.PendingCall pendingCall,
							Exception error, Bundle data) {
						Log.e("ActivityFacebook",
								String.format("Error: %s", error.toString()));
					}

					@Override
					public void onComplete(
							FacebookDialog.PendingCall pendingCall, Bundle data) {
						Log.i("ActivityFacebook", "Success!");
						if (FacebookDialog.getNativeDialogDidComplete(data)) {
							Toast.makeText(getApplicationContext(),
									"Shared to your Timeline",
									Toast.LENGTH_SHORT).show();
						}
					}
				});
	}

	private class AsyncGetCommentList extends
			AsyncTask<String, Comment, ArrayList<Comment>> {

		@Override
		protected ArrayList<Comment> doInBackground(String... params) {

			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("article_id", params[0]);
			param.put("client_id", MyApplication.USER_ID);

			JSONObject jsonObject = null;
			ArrayList<Comment> listComments = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/get_article_comment", param);
				// Parse the JSON Object
				JSONParser parser = new JSONParser();
				listComments = parser.parserComment(jsonObject);
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return listComments;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			llLoading.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPostExecute(ArrayList<Comment> result) {

			listComments.clear();
			if (result != null && result.size() != 0) {
				for (int i = 0; i < result.size(); i++) {
					listComments.add(result.get(i));
				}
				ArrayList<Comment> listReply = new ArrayList<Comment>();
				for (int i = 0; i < listComments.size(); i++) {
					listReply = new ArrayList<Comment>();
					for (int j = 0; j < listComments.get(i).getListReply().size(); j++) {
						listReply.add(listComments.get(i).getListReply().get(j));
					}
					listReplys.put(listComments.get(i).getCommentId(),
							listReply);
				}
				commentAdapter.notifyDataSetChanged();
			} /*
			 * else { AlertDialog.Builder builder = new AlertDialog.Builder(
			 * getActivity()); //builder.setTitle("Not found result!");
			 * builder.setMessage("Not found result!");
			 * builder.setNegativeButton("Yes", new
			 * DialogInterface.OnClickListener() {
			 * 
			 * @Override public void onClick(DialogInterface dialog, int which)
			 * { //getActivity().finish(); } }); builder.show(); }
			 */
			llLoading.setVisibility(View.GONE);
		}
	}

	private class AsyncPostComment extends AsyncTask<String, Void, String> {
		String mArticleID;
		String mTextComment;

		public AsyncPostComment(String articleId, String textComment) {
			mArticleID = articleId;
			mTextComment = textComment;
		}

		@Override
		protected String doInBackground(String... params) {
			String commentId = null;
			// post comment
			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("article_id", mArticleID);
			param.put("parent_id", "0");
			param.put("client_id", MyApplication.USER_ID);
			param.put("content", mTextComment);

			JSONObject jsonObject = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/set_comment", param);
				JSONParser parser = new JSONParser();
				commentId = parser.parserPostComment(jsonObject);
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			return commentId;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			llLoading.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPostExecute(String result) {
			if(result != null) {
				// get current time
				SimpleDateFormat format = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss", Locale.US);
				String currentTime = format.format(System.currentTimeMillis());
				// create comment obj
				Comment comment = new Comment();
				comment.setArticleId(mArticleID);
				comment.setCommentId(result);
				comment.setClientId(MyApplication.USER_ID);
				comment.setContent(mTextComment);
				comment.setCreatedAt(currentTime);
				comment.setUpdatedAt(currentTime);
				comment.setIsDeleted("0");
				comment.setLikeCount(0);
				comment.setDislikeCount(0);
				comment.setListReply(new ArrayList<Comment>());
				listComments.add(comment);
				listReplys.put(result, new ArrayList<Comment>());
				commentAdapter.notifyDataSetChanged();
			} else {
				Toast.makeText(getApplicationContext(),
						"An unexpected error has occurred when comment.",
						Toast.LENGTH_SHORT).show();
			}
			llLoading.setVisibility(View.GONE);
		}
	}
	
	private class AsyncSetBookmark extends	AsyncTask<String, Void, Integer> {

		@Override
		protected Integer doInBackground(String... params) {

			int re = -1;
			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("article_id", params[0]);
			param.put("client_id", MyApplication.USER_ID);

			JSONObject jsonObject = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/set_bookmark", param);
				re = jsonObject.getInt("status");
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
				return re;
			} catch (IOException e1) {
				e1.printStackTrace();
				return re;
			} catch (JSONException e) {
				e.printStackTrace();
				return re;
			}
			return re;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Integer result) {

			if (result == 0) {
				ContentValues values = new ContentValues();
				
				//insert new if has not bookmark yet
				if (articleTableAdapter.getArticleId(article.getArticleId()) == null) {
					values.put("article_id", article.getArticleId());
					values.put("title", article.getTitle());
					values.put("site", article.getSite());
					values.put("cmt_count", article.getCmtCount());
					values.put("image", article.getImage());
					values.put("url", article.getUrl());
					values.put("overview", article.getOverview());
					values.put("is_bookmark", "1");
					articleTableAdapter.addArticle(values);
					// set color for button
					llBookmark.setSelected(true);
					tvBookmark.setText(getString(R.string.btnBookmarkAlready)
							.toString().trim());
					Toast.makeText(getApplicationContext(), "Bookmarked this article!",
							Toast.LENGTH_SHORT).show();
				} else if ("0".equals(articleTableAdapter.getArticleId(article.getArticleId()))) {
					//update lai neu trong DB co id nay roi
					values.put("is_bookmark", "1");
					articleTableAdapter.updateArticle(article.getArticleId(), values);
					llBookmark.setSelected(true);
					tvBookmark.setText(getString(R.string.btnBookmarkAlready)
							.toString().trim());
					Toast.makeText(getApplicationContext(), "Bookmarked this article!",
							Toast.LENGTH_SHORT).show();
				}
			} else {
				//fail
				Toast.makeText(getApplicationContext(), "Bookmark fail.", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private class AsyncRemoveBookmark extends	AsyncTask<String, Void, Integer> {

		@Override
		protected Integer doInBackground(String... params) {

			int re = -1;
			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("article_id", params[0]);
			param.put("client_id", MyApplication.USER_ID);

			JSONObject jsonObject = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/remove_bookmark", param);
				re = jsonObject.getInt("status");
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
				return re;
			} catch (IOException e1) {
				e1.printStackTrace();
				return re;
			} catch (JSONException e) {
				e.printStackTrace();
				return re;
			}
			return re;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Integer result) {

			if (result == 0) {
				ContentValues values = new ContentValues();
				
				if ("1".equals(articleTableAdapter.getArticleId(article.getArticleId()))) {
					//remove if has been bookmarked
					values.put("is_bookmark", "0");
					articleTableAdapter.updateArticle(article.getArticleId(), values);
					llBookmark.setSelected(false);
					tvBookmark.setText(getString(R.string.btnBookmarkNotyet).toString()
							.trim());
					Toast.makeText(getApplicationContext(),
							"Removed bookmark this article!", Toast.LENGTH_SHORT)
							.show();
				}
			} else {
				//fail
				Toast.makeText(getApplicationContext(), "Remove bookmark fail.", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private class AsyncSetShareInApp extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {

			String res = null;
			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("article_id", params[0]);
			param.put("type", params[1]);

			JSONObject jsonObject = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/set_sharet_inapp", param);
				res = jsonObject.getString("status");
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return res;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {

			if (result != null) {
				// TODO
			}
		}
	}

	@Override
	protected void onStart() {
		//overridePendingTransition(R.anim.slide_out_right, R.anim.slide_in_left);
		super.onStart();
	}
	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
	}
}
